#!/usr/bin/node

const SerialPort = require('serialport');

function usage() {
    console.error("Usage:");
    console.error('node ain2vcd.js path');
    console.error('');
    console.error('Arguments:');
    console.error('  path: serial device path, for example: /dev/ttyUSB0');
    console.error('');

    process.exit();
}

if(process.argv.length <= 2) {
    usage();
}

var serialPath = process.argv[2];
var serialOptions = {
    autoOpen: false,
    baudRate: 1000000
}

var port = new SerialPort(serialPath, serialOptions);
port.open(port_on_open);

function port_on_open(err) {
    if(err) {
        console.error(err.message);
        process.exit();
    }

    var count = 2;
    var ain_last = 0;
    var ain = 0;
    var ain_hi_valid = false;

    port.on('error', port_on_error);
    port.on('data', port_on_data);
    process.on('SIGINT', process_on_sigint);
    process.stdin.on('data', stdin_on_data);
    port.flush();
    port.write('eee');
    write_vcd_header();

    function write_vcd_header() {
      console.log('$version ain2vcd $end');
      console.log('$timescale 1000us $end');
      console.log('$scope module microampere $end');
      console.log('$var real 12 # ain [11:0] $end');
      console.log('$upscope $end');
      console.log('$enddefinitions $end');
      console.log('$dumpvars');
      console.log('r10 #');
      console.log('$end');
      console.log('#1\nr0 #');
    }

    function port_on_error(err) {
      console.error(err.message);
      process.exit(1);
    }

    function port_on_data(data) {
      for(var i = 0; i < data.length; i++) {
          if((data[i] & 0xc0) == 0x80) {
              ain_hi_valid = true;
              ain = (data[i] & 0x3f) << 6;
          } else if((data[i] & 0xc0) == 0x40) {
              if(ain_hi_valid) {
                  ain |= data[i] & 0x3f;
                  if(ain_last != ain) {
                      console.log('#%d\nr%d #', count, ain);
                      ain_last = ain;
                  }
                  count++;
              } else {
                  console.error('ERROR: Unexpected data order.');
              }
              ain_hi_valid = false;
          } else {
              console.error('ERROR: Unexpected data: %d.', data[i]);
              ain_hi_valid = false;
          }
      }
    }

    function process_on_sigint() {
      port.write('ddd', port_on_write);
    }

    function port_on_write() {
      process.exit();
    }

    function stdin_on_data(data) {
      port.write(data);
    }
}
